Java获取文件ContentType |
您所在的位置:网站首页 › 获取content 路径 › Java获取文件ContentType |
在上传文件时,为了安全会做一些校验,检查HTTP Header中的Content-Type就是其中的一种,今天就来看下上传文件时的Content-Type是如何获取的: 先来看些常用的mimetype表: text/plain(纯文本) text/html(HTML文档) text/javascript(js代码) application/xhtml+xml(XHTML文档) image/gif(GIF图像) image/jpeg(JPEG图像) image/png(PNG图像) video/mpeg(MPEG动画) application/octet-stream(二进制数据) application/pdf(PDF文档) application/(编程语言) 该种语言的代码 application/msword(Microsoft Word文件) message/rfc822(RFC 822形式) multipart/alternative(HTML邮件的HTML形式和纯文本形式,相同内容使用不同形式表示) application/x-www-form-urlencoded(POST方法提交的表单) multipart/form-data(POST提交时伴随文件上传的表单) 代码: import java.io.File; import java.io.IOException; import java.net.FileNameMap; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.activation.MimetypesFileTypeMap; /** * @ClassName: GetContectType * @date: 2019年5月16日 */ public class GetContectType { /** * 方式一 * 该方式只支持本地文件,有时候会存在获取为null的情况 * @param fileUrl */ public static String getContentTypeByLocal(String fileUrl) { String contentType = null; Path path = Paths.get(fileUrl); try { contentType = Files.probeContentType(path); } catch (IOException e) { e.printStackTrace(); } System.out.println("getContentTypeByLocal, File ContentType is : " + contentType); return contentType; } /** * 方式二 * 该方式支持本地文件,也支持http/https远程文件 * @param fileUrl */ public static String getContentType(String fileUrl) { String contentType = null; try { contentType = new MimetypesFileTypeMap().getContentType(new File(fileUrl)); } catch (Exception e) { e.printStackTrace(); } System.out.println("getContentType, File ContentType is : " + contentType); return contentType; } /** * 方式三 * @param fileUrl,有时候会存在获取为null的情况 */ public static String getContentTypeByType(String fileUrl) { String contentType = null; try { FileNameMap fileNameMap = URLConnection.getFileNameMap(); contentType = fileNameMap.getContentTypeFor(fileUrl); } catch (Exception e) { e.printStackTrace(); } System.out.println("getContentTypeByType, File ContentType is : " + contentType); return contentType; } public static void main(String[] args) { // 文件路径 String fileUrl = "C:\\Users\\***\\Downloads\\2.jpg"; // 方式一 getContentTypeByLocal(fileUrl); // 方式二,推荐使用 getContentType(fileUrl); // 方式三 getContentTypeByType(fileUrl); } }执行结果: |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |